<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon noTitleExplain">
      <el-form
        :model="formData"
        label-width="100px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="规则名称：" prop="ruleName">
              <el-input
                v-model="formData.ruleName"
                class="mWidth"
                placeholder="请输入规则名称"
                @blur="formData.ruleName = changeValue($event)"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="打卡部门：" prop="department">
              <div class="treeBox clearfix">
                <el-col :span="12" class="col-position tree">
                  <el-tree
                    :data="orglist"
                    :props="defaultProps"
                    @node-click="handleNodeClick"
                    :expand-on-click-node="expandOnClick"
                    default-expand-all
                    ref="tree"
                  ></el-tree>
                </el-col>
                <el-col :span="12" class="col-position selectedDepartment">
                  <p>已选择部门</p>
                  <ul id="choiceNameBox">
                    <li
                      v-for="(item, index) of choiceName"
                      :key="index"
                      :id="'department' + index"
                      class="department"
                      v-bind:selectedVal="item.value"
                    >
                      <span class="name"> {{ item.label }}</span
                      ><span class="fr del" @click="toDel($event, item, index)"
                        >删除</span
                      >
                    </li>
                  </ul>
                </el-col>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="打卡地点：" prop="address">
              <el-button
                type="primary"
                style="margin-left: 0"
                class="commonBut saveBtn funComBut addbtn"
                icon="icon iconfont icontianjia"
                v-show="!addressFormData.address"
                @click="addAddress"
              >
                <span class="opetareText">添加</span>
              </el-button>
              <el-button
                type="primary"
                style="margin-left: 0"
                class="commonBut saveBtn funComBut edit"
                icon="icon iconfont iconbianji"
                v-show="addressFormData.address"
                @click="editAddress"
              >
                <span class="opetareText">修改</span>
              </el-button>
              <!-- <el-button type="primary" icon="icon iconfont icontianjia" @click="addAddress" class="commonBtn"  v-show="!addressFormData.address"></el-button>
              <el-button type="primary" icon="icon iconfont iconbianji" @click="editAddress" class="commonBtn"  v-show="addressFormData.address"></el-button> -->
              <div class="addressNameInfo" v-show="addressFormData.address">
                {{ addressFormData.address }}
                <div class="range">
                  &nbsp;&nbsp;({{ addressFormData.range }}米内)
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom" style="margin-top: 18px">
          <el-col :span="24" class="col-position">
            <el-form-item label>
              <el-button
                class="commonBut saveBtn"
                @click="toSaveRule"
                :loading="isAdd"
                >保存</el-button
              >
              <el-button class="commonBut" @click="toQyAttendance"
                >取消</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!--打卡地址弹窗-->
    <setMap
      v-if="isShowDialog"
      :addressFormData="addressFormData"
      @editSubmit="editSubmit"
      :type="type"
      :isJZ="isJZ"
    ></setMap>
  </div>
</template>

<script>
import setMap from '@/components/publicCom/setMap'

export default {
  name: 'addPunchCardRule',
  data() {
    var checkLat = (rule, value, callback) => {
      var that = this
      var address = that.addressFormData.address.replace(/\s/g, '')

      setTimeout(function () {
        if (
          !that.addressFormData.lat ||
          !address ||
          (that.flag == false && !that.addressFormData.lat)
        ) {
          that.flag = true
          return callback(new Error('请输入有效地址'))
        } else {
          callback()
        }
      }, 1000)
    }
    var checDepartment = (rule, value, callback) => {
      this.$nextTick(function () {
        if (this.choiceName.length < 1) {
          return callback(new Error('请选择打卡部门'))
        } else {
          callback()
        }
      })
    }
    return {
      show: false,
      back: true,
      titleText: '',
      formData: {
        ruleName: '',
      },
      //验证
      formRules: {
        ruleName: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入规则名称',
            trigger: 'blur',
          },
        ],
        address: [
          {
            required: true,
            validator: checkLat,
            // pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            // message: "请添加打卡地址",
            trigger: 'blur',
          },
        ],
        department: [
          {
            required: true,
            validator: checDepartment,
            // pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            // message: "请选择打卡部门",
            trigger: 'blur',
          },
        ],
      },
      orglist: [],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      choiceName: [],
      // 弹窗
      formVisible: false,
      addressFormData: {
        range: 100,
        address: '',
        lat: '',
        lon: '',
      },
      expandOnClick: false,
      selectedOrglist: [],
      //编辑，之前的打卡点id
      id: '',
      type: '',
      isAdd: false,
      flag: true,
      isShowDialog: false,
      isJZ: false, //是否是建筑
    }
  },
  components: {
    setMap,
  },
  computed: {},
  created() {
    this.getOrglist()
    this.id = this.$route.query.id
    this.type = this.$route.query.type

    if (this.type == 'edit') {
      this.titleText = '编辑打卡规则'
      this.formData.ruleName = this.$route.query.name
      this.getRuleList()
    } else {
      this.titleText = '添加打卡规则'
    }
  },

  methods: {
    handleNodeClick(item) {
      const { label, value } = item
      if (this.choiceName.length) {
        let flag = true
        this.choiceName.forEach((items) => {
          if (items.id == item.id) {
            flag = false
          }
        })
        if (flag) {
          this.choiceName.push({ label, value })
          this.$refs.formData.validateField('department')
        }
      } else {
        this.choiceName.push({ label, value })
        this.$refs.formData.validateField('department')
      }
    },
    //删除选中部门
    toDel(e, item, index) {
      this.choiceName.splice(index, 1)
      this.$refs.formData.validateField('department')
    },
    closeDialog() {},
    toSaveRule() {
      this.isAdd = true
      // return
      this.selectedOrglist = []
      for (var i = 0; i < this.choiceName.length; i++) {
        let item = this.choiceName[i]
        this.selectedOrglist.push({ orgId: item.value, type: 1 })
      }

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.saveRule()
        } else {
          this.isAdd = false
        }
      })
    },
    saveRule() {
      var container = []
      container[0] = this.addressFormData

      var data = {
        name: this.formData.ruleName,
        attendancePoints: JSON.stringify(container),
        attendanceOrgs: JSON.stringify(this.selectedOrglist),
      }
      var url = ''
      if (this.type == 'edit') {
        data.id = this.id
        url = 'api-att/nc/attrule/expand/editrule'
      } else {
        url = 'api-att/nc/attrule/expand/addrule'
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              var text = this.type == 'edit' ? '编辑成功' : '添加成功'
              this.$message({
                message: text,
                type: 'success',
              })
              // this.goBack();
              this.$router.push('/home/attendance/punchCardRuleList')
              this.$store.commit('CHANGE_SLIDER_NAME', {
                oldUrl: '/home/attendance/qyAttendance',
                newUrl: this.$router.currentRoute.fullPath,
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
              this.isAdd = false
            }
          },
          (response) => {
            this.isAdd = false
          }
        )
        .catch((error) => {})
    },
    addAddress() {
      this.formVisible = true
      this.addressFormData.range = 100
      this.addressFormData.address = ''
      this.addressFormData.lat = ''
      this.addressFormData.lon = ''
      this.isShowDialog = true
    },
    editSubmit() {
      this.isShowDialog = true
      return
      this.$refs.addressFormData.validate((valid) => {
        if (valid) {
          this.addressFormData.address = $('#suggestId').val()
          this.$refs.formData.validateField('address')
          this.formVisible = false
        } else {
        }
      })
    },
    //弹窗关闭
    editSubmit() {
      this.isShowDialog = false
      this.$refs.formData.validateField('address')
    },
    // 点击编辑
    editAddress() {
      this.isShowDialog = true
    },
    //获取部门
    getOrglist() {
      this.axios({
        method: 'post',
        url: 'api-att/nc/attendance/expand/orgarc',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.orglist = response.data.result
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    //获取之前的打卡规则
    getRuleList() {
      var data = {
        id: this.id,
      }
      this.axios({
        method: 'post',
        url: 'api-att/nc/attrule/expand/ruledetail',
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.addressFormData.range =
                response.data.result.attendancePointVos[0].range
              this.addressFormData.address =
                response.data.result.attendancePointVos[0].address
              this.addressFormData.lat =
                response.data.result.attendancePointVos[0].lat
              this.addressFormData.lon =
                response.data.result.attendancePointVos[0].lon

              for (
                var i = 0;
                i < response.data.result.attendanceOrgVos.length;
                i++
              ) {
                var item = response.data.result.attendanceOrgVos[i]
                this.choiceName.push({ label: item.orgName, value: item.orgId })
              }
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    toQyAttendance() {
      this.goBack()
    },
    goBack() {
      this.$router.push('/home/attendance/punchCardRuleList')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/attendance/qyAttendance',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style scoped lang="less">
.department {
  transform-origin: left;
  .icon {
    color: #009588;
    font-size: 14px;
    vertical-align: middle;
    float: left;
    margin-right: 5px;
  }
  .name {
    // float: left;
    transform-origin: left;
    display: inline-block;
    font-style: normal;
    width: 245px;
    overflow: hidden; /*超出的部分隐藏起来。*/
    white-space: nowrap; /*不显示的地方用省略号...代替*/
    text-overflow: ellipsis; /* 支持 IE */
  }
  .del {
    transform-origin: left;
  }
}

.row-padding-bottom {
  margin-bottom: 10px;
}

.mainCon {
  padding: 40px;
  height: calc(100% - 67px);
  // /deep/ .el-form{
  //   padding: 50px 60px;
  //   // .el-input__inner{
  //   //   width: 340px;
  //   // }
  // }
  .treeBox {
    width: 666px;
    // width: 200px;
    background: #f5f7fa;
    border: 1px solid #dee5f4;
    border-radius: 4px;
    padding: 12px 16px 12px 0;
    .tree {
      // padding:4px;
      height: 235px;
      overflow: auto;
      border-right: 1px solid #dee5f4;
      /deep/ .el-tree {
        background: #f5f7fa;
        .el-tree-node__label {
          overflow: hidden;
          text-overflow: ellipsis; /* 超出部分显示省略号 */
          white-space: nowrap; /*规定段落中的文本不进行换行 */
          margin-left: 0;
        }
        // .el-tree-node__expand-icon.is-leaf{
        //   color: #C0C4CC;
        // }
      }
    }
    .selectedDepartment {
      padding: 12px;
      margin-top: -12px;
      padding-right: 0;
      height: 235px;
      overflow: auto;
      p {
        font-size: 14px;
        line-height: 26px;
        color: #999;
        border-bottom: 1px solid #dee5f4;
      }
      .del {
        font-size: 14px;
        color: #409eff !important;
        cursor: pointer;
      }
    }
  }

  .addressNameInfo {
    line-height: 28px;
    width: 666px;
    i {
      font-size: 18px;
      color: #009588;
      vertical-align: middle;
    }
    .range {
      color: #999;
      display: initial;
    }
  }
}

#choiceNameBox li {
  line-height: 40px;
  height: 40px;
}

@media screen and (max-width: 1280px) {
  .mainCon .el-form {
    padding: 50px 20px;
  }

  .mainCon .treeBox {
    width: 630px;
  }

  .department .name {
    width: 220px;
  }
}
</style>
